package Demo04.demo06;
 
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class FileService extends Thread{
 
	private Socket s;
	private File dir;
	
	public FileService(Socket s){
		this.s = s;
	}
 
	public void setDir(File dir) {
		this.dir = dir;
	}
	
	@Override
	public void run() {
		BufferedInputStream bis = null;
		try {
			//1.获取目录中的所有文件列表
			File[] files = dir.listFiles();
			//准备map集合以编号->文件的方式存储文件信息
			Map<String,File> map = new HashMap<>();
			for(int i = 0;i<files.length;i++){
				map.put(String.valueOf(i + 1), files[i]);
			}
			//2.将文件列表发送到客户端
			ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
			//发送对象到客户端Socket中
			oos.writeObject(map);
			//3.接收客户端的指令(需要下载的文件编号)
			BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
			String no = br.readLine();
			//4.根据文件编号找到指定文件并获取该文件的输入流
			File target = map.get(no);
			bis = new BufferedInputStream(new FileInputStream(target));
			//5.获取客户端Socket的输出流将读取的文件内容写出去
			//获取基于socket的输出流，向客户端发送文件数据
			BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
			byte[] b = new byte[1024];
			int len = 0;
			while((len = bis.read(b)) != -1){
				bos.write(b, 0, len);
			}
			bos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(s != null){
					s.close();
				}
				if(bis != null){
					bis.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}